package com.android.fitcontrol;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.android.fitcontrol.bean.Exercise;
import com.android.fitcontrol.bean.Many;
import com.android.fitcontrol.database.DBConnector;

public class ExerciseDetailActivity extends Activity {

	public static final int IDM_DELETE = 101;

	private ActionBar actionBar;
	private DBConnector connector;
	private Cursor cursor;
	private long id; // exercise id
	private String selection; // selection to get sets from DB, which is belong
								// to the exercise with id
	private String[] selectionArgs; // args of selection
	private ListView listView;
	private DetailListAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exercise_detail_layout);

		try {
			id = Long.valueOf(getIntent().getExtras().getString(Exercise._ID));// getting
																				// exercise
																				// id
			connector = new DBConnector(this);
			selection = Many.EXERCISE_ID + " = ?"; // getting all sets with
													// specified exercise ID
			selectionArgs = new String[] { String.valueOf(id) };
			cursor = querySets(); // getting results of query sets

			Exercise exercise = (Exercise) connector.selectOneRowFromTable(
					Exercise.TABLE_NAME, (int) id); // getting parent exercise

			actionBar = getActionBar();
			//actionBar.setDisplayHomeAsUpEnabled(true);

			listView = (ListView) findViewById(R.id.exercise_detail_list);
			EditText edit = (EditText) findViewById(R.id.exercise_name);
			edit.setText(exercise.getExerciseName());
			adapter = new DetailListAdapter(this,
					R.layout.exercise_detail_list_item, cursor, new String[] {
							Many.PLANNED_COUNT, Many.PLANNED_WEIGHT,
							Many.DONE_COUNT, Many.DONE_WEIGHT }, new int[] {
							R.id.planned_count_edit_text,
							R.id.planned_weight_edit_text,
							R.id.done_count_edit_text,
							R.id.done_weight_edit_text });
			listView.setAdapter(adapter);
			registerForContextMenu(listView);// we need context menu only on
												// listView,
			// because the place of user touch is defines set, which need to
			// delete

			final Button mAddButton = (Button) findViewById(R.id.add_exercise_btn);
			// adding new set
			mAddButton.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					// TODO Auto-generated method stub
					Many many = new Many();// initialize empty set
					many.setExercise_ID((int) id);// it is belong to the
													// exercise with ID
					try {
						// here we need to check if the user changed some fields
						// before adding new set, because adding new set updates
						// cursor and after this we lost changed data. So we
						// need to ask the user if he wants to save changed
						// data.
						// if no - we ignore changes and adding new set and
						// update cursor.
						// if yes - we save changed data and after this adding
						// new set
						if (adapter.isModified()) { // check - if the user
													// changed data (some of
													// editFields)
							AlertDialog.Builder builder = new AlertDialog.Builder(
									ExerciseDetailActivity.this);
							builder.setMessage(getResources().getString(
									R.string.dialog_save_changed_data));// initialize
																		// dialog
							builder.setPositiveButton(
									R.string.dialog_yes_button,
									new DialogInterface.OnClickListener() {

										// case, when the user wants to save
										// data
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											// saving data
											if (listView.getCount() > 0) {
												for (int i = 0; i < listView
														.getCount(); i++) {
													Many man = adapter
															.getManyAtPosition(i);// getting
																					// changed
																					// data
																					// from
																					// inner
																					// array
																					// of
																					// adapter
													connector
															.update(man,
																	Many._ID
																			+ "="
																			+ man.get_ID(),
																	null);// update
												}
											}
											Many many = new Many();
											many.setExercise_ID((int) id);// adding
																			// new
																			// set
											connector.insert(many);
											cursor = querySets();// requery all
																	// sets
											adapter.changeCursor(cursor);// reinitializing
																			// adapter
											listView.setSelection(cursor
													.getCount() - 1); // setting
																		// focus
																		// on
																		// the
																		// added
																		// set
										}
									});

							builder.setNegativeButton(
									R.string.dialog_no_button,
									new DialogInterface.OnClickListener() {

										// case, when the user does not want to
										// save data. we ignore changes and
										// adding new set without save changes
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											// adding new empty set and updating
											// cursor and listView
											Many many = new Many();
											many.setExercise_ID((int) id);
											connector.insert(many);
											cursor = querySets();
											// we need to update adapter,
											// because some problems with
											// synchronization
											adapter = new DetailListAdapter(
													ExerciseDetailActivity.this,
													R.layout.exercise_detail_list_item,
													cursor,
													new String[] {
															Many.PLANNED_COUNT,
															Many.PLANNED_WEIGHT,
															Many.DONE_COUNT,
															Many.DONE_WEIGHT },
													new int[] {
															R.id.planned_count_edit_text,
															R.id.planned_weight_edit_text,
															R.id.done_count_edit_text,
															R.id.done_weight_edit_text });
											listView.setAdapter(adapter);
											//
											listView.setSelection(cursor
													.getCount() - 1);
										}
									});
							builder.show();
						} else {
							// data wasn't changed and we just inserting new
							// empty set
							connector.insert(many);
							cursor = querySets();
							adapter.changeCursor(cursor);
							listView.setSelection(cursor.getCount() - 1);
						}
					} catch (Exception exp) {
						exp.printStackTrace();
					}
				}
			});

			final Button mSaveButton = (Button) findViewById(R.id.save_btn);
			mSaveButton.setOnClickListener(new OnClickListener() {

				// save changes
				public void onClick(View v) {
					// TODO Auto-generated method stub
					try {
						// updating exercise name
						Exercise exercise = (Exercise) connector
								.selectOneRowFromTable(Exercise.TABLE_NAME,
										(int) id);
						EditText edit = (EditText) findViewById(R.id.exercise_name);
						exercise.setExerciseName(edit.getText().toString());
						connector.update(exercise, Exercise._ID + "=" + id,
								null);

						// updating all items of list
						if (listView.getCount() > 0) {
							for (int i = 0; i < listView.getCount(); i++) {
								Many man = adapter.getManyAtPosition(i);// getting
																		// item
																		// from
																		// adapter
								connector.update(man,
										Many._ID + "=" + man.get_ID(), null);
							}
							cursor = querySets();// requery cursor
							adapter.changeCursor(cursor);// change cursor of
															// adapter and
															// respectively
															// update listView
							Toast.makeText(
									ExerciseDetailActivity.this,
									getResources().getString(
											R.string.successful_save),
									Toast.LENGTH_LONG).show();// message:
																// success save
						} else {
							Toast.makeText(
									ExerciseDetailActivity.this,
									getResources().getString(
											R.string.error_nothing_to_update),
									Toast.LENGTH_LONG).show();// no data to
																// update
						}
					} catch (Exception exp) {
						exp.printStackTrace();
						Toast.makeText(ExerciseDetailActivity.this,
								"Error during save", Toast.LENGTH_LONG).show();// some
																				// errors
					}
				}
			});
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}

	/**
	 * this method queries all sets, which belong to the choosen exercise
	 * 
	 * @return cursor
	 */
	private Cursor querySets() {
		Cursor cursor = connector.query(Many.TABLE_NAME, null, selection,
				selectionArgs, null, null, Exercise._ID);
		return cursor;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Intent backIntent = new Intent(this, ExerciseListActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;
		case R.id.action_bar_logout_item:
			connector.delete("user", -1);
			connector.close();
			Intent loginIntent = new Intent(this, LoginActivity.class);
			loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(loginIntent);
			finish();
			break;
		case R.id.action_bar_calendar_item:
			Intent monthScheduleIntent = new Intent(this, MonthScheduleActivity.class);
			monthScheduleIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(monthScheduleIntent);
			finish();
		}
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		// one more check to build context menu only on the listView
		if (v.getId() == R.id.exercise_detail_list
				|| v.getId() == R.id.exercise_detail_list_item
				|| v.getId() == R.id.sets_table) {
			menu.add(Menu.NONE, IDM_DELETE, Menu.NONE, getResources()
					.getString(R.string.context_menu_delete));
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		// context deleting of set
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();// this object contains very important data:
		// position of the selected item
		if (item.getItemId() == IDM_DELETE) {
			// same case as for adding new set
			// we need to check if the user changed some data
			if (adapter.isModified()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						ExerciseDetailActivity.this);
				builder.setMessage(getResources().getString(
						R.string.dialog_save_changed_data));
				builder.setPositiveButton(R.string.dialog_yes_button,
						new DialogInterface.OnClickListener() {

							// saving data if user confirm dialog and realize
							// removing of set
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								if (listView.getCount() > 0) {
									for (int i = 0; i < listView.getCount(); i++) {
										Many man = adapter.getManyAtPosition(i);
										connector.update(man, Many._ID + "="
												+ man.get_ID(), null);
									}
								}

								int many_id = (int) adapter
										.getItemId(info.position);
								connector.delete(Many.TABLE_NAME, many_id);
								cursor = querySets();
								adapter.changeCursor(cursor);
								if (cursor.moveToFirst()) {
									listView.setSelection(0);
								}
							}
						});

				builder.setNegativeButton(R.string.dialog_no_button,
						new DialogInterface.OnClickListener() {

							// just removing of the selected set
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								int many_id = (int) adapter
										.getItemId(info.position);
								adapter.notifyDataSetChanged();// need to
																// refresh
																// listView
								connector.delete(Many.TABLE_NAME, many_id);
								cursor = querySets();
								adapter = new DetailListAdapter(
										ExerciseDetailActivity.this,
										R.layout.exercise_detail_list_item,
										cursor, new String[] {
												Many.PLANNED_COUNT,
												Many.PLANNED_WEIGHT,
												Many.DONE_COUNT,
												Many.DONE_WEIGHT }, new int[] {
												R.id.planned_count_edit_text,
												R.id.planned_weight_edit_text,
												R.id.done_count_edit_text,
												R.id.done_weight_edit_text });
								listView.setAdapter(adapter);
								if (cursor.moveToFirst()) {
									listView.setSelection(0);
								}
							}
						});
				builder.show();
			} else {
				// data wasn't changed, just removing choosen by context menu
				// set
				int many_id = (int) adapter.getItemId(info.position);
				connector.delete(Many.TABLE_NAME, many_id);
				cursor = querySets();
				adapter.changeCursor(cursor);
				if (cursor.moveToFirst()) {
					listView.setSelection(0);
				}
			}
			return true;
		} else {
			return super.onContextItemSelected(item);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	@Override
	protected void onStop() {
		// close all resources
		// TODO Auto-generated method stub
		super.onStop();
		cursor.close();
		connector.close();
	}
}
